package com.example.ui.share;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.Communication;
import com.example.service.MainService;
import com.example.ui.contact.face.CirclePageIndicator;
import com.example.ui.contact.face.FaceAdapter;
import com.example.ui.contact.face.FacePageAdeapter;
import com.example.ui.contact.face.FaceUtil;
import com.example.ui.contact.face.FaceViewPager;
import com.example.ui.contact.face.FaceViewPager.TransitionEffect;
import com.example.ui.homepage.HomePageView;
import com.example.ui.leftmenu.Item05View;
import com.example.util.BitmapLoad;
import com.example.util.Util;

public class PublishCircleShareActivity extends Activity {
	public static final int FAIL =0;
	public static final int DELETE_SHARE_PIC_SUCCESS =1;
	public static final int ADD_SHARE_SUCCESS =2;
	
	public static final int CAMERA_RESULT = 100;// 拍照
	 public static final int ALBUM_RESULT = 200;// 相册
	public static final int SAVE_PHOTO_RESULT = 300;// 保存
	
	private String Filename = "";
	private String imagenames = "";

	
	//表情控件
	FaceUtil faceUtil = HSApplication.getInstance().getFaceUtil();
	private LinearLayout faceLinearLayout;
	private FaceViewPager faceViewPager;
	private boolean isFaceShow = false;
	private InputMethodManager imm;
	private List<String> keys;
	private int currentPage = 0;
	
	
	private Button titleLeftBtn, titleRightBtn;
	private TextView titleText, myLocation;
	private EditText contentEdit;
	private CheckBox photoImgBtn, positionImgBtn, myImagesCheckBox;
	private ImageView headImg, atImgBtn, faceImgBtn, myImages;
	private GridView gridView;
	private LinearLayout gridLayout;
	private FrameLayout imgLayout;

	private Intent myIntent;
	private String headPath, type, albumImg,circleId;
	private String[] imgArr;
	private List<String> imgList = new ArrayList<String>();
	private String myAddr = "";//我的位置信息

	public static Handler handler;
	private ProgressDialog pro;
	StringBuffer ss = new StringBuffer();
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.publish_share);
		pro = new ProgressDialog(this);
		pro.setMessage("请稍候...");
		pro.setCancelable(true);
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		
		findView();
		titleClick();
		clickListener();
		initFacePage();
		
		myIntent = getIntent();
		headPath = myIntent.getStringExtra("myHead");
		type = myIntent.getStringExtra("type");

		headImg.setImageBitmap(BitmapLoad.loadBitmap(this, headPath));// 设置头像

		if ("album".equals(type)) {// 本地图片
			albumImg = myIntent.getStringExtra("albumImg");
			imgArr=myIntent.getStringArrayExtra("imgArr");
			for(int i=0;i<imgArr.length;i++){
				imgList.add(imgArr[i]);
			}
			
			album();
			
		} else if ("edit".equals(type)) {// 发表分享
			circleId=myIntent.getStringExtra("circleId");
			publishEdit();
			
		} else if ("camera".equals(type)) {// 照相机
			camera();
			
		}
		
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case FAIL:
					Util.toast(PublishCircleShareActivity.this, "服务器连接失败");
					pro.cancel();
					break;
				case DELETE_SHARE_PIC_SUCCESS:
					if(HSApplication.uploadTempImgList.size()==0){
						
					}else{
						for(int i=0;i<HSApplication.uploadTempImgList.size();i++){
							ss.append(HSApplication.uploadTempImgList.get(i).toString()).append("|");
						}
					}
					pro.cancel();
					break;
				case ADD_SHARE_SUCCESS:
					pro.cancel();
					//CircleHomeActivity.circleAdapter.notifyDataSetChanged();
					finish();
					break;

				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
		
	}

	private void findView() {
		titleLeftBtn = (Button) findViewById(R.id.layout_title_left_btn);
		titleRightBtn = (Button) findViewById(R.id.layout_title_right_btn);
		titleText = (TextView) findViewById(R.id.layout_title_middle_text);
		titleLeftBtn.setText("返回");
		titleText.setText("发表分享");
		titleRightBtn.setText("发表");

		headImg = (ImageView) findViewById(R.id.publish_share_head);
		contentEdit=(EditText)findViewById(R.id.publish_share_edit);
		gridView = (GridView) findViewById(R.id.publish_share_gridview_photos);
		photoImgBtn = (CheckBox) findViewById(R.id.publish_share_photo);
		positionImgBtn = (CheckBox) findViewById(R.id.publish_share_position);
		atImgBtn = (ImageView) findViewById(R.id.publish_share_at);
		faceImgBtn = (ImageView) findViewById(R.id.publish_share_face);
		myLocation = (TextView) findViewById(R.id.publish_share_position_text);
		myImages = (ImageView) findViewById(R.id.publish_share_photos);
		gridLayout = (LinearLayout) findViewById(R.id.publish_share_gridview_photos_layout);
		imgLayout = (FrameLayout) findViewById(R.id.publish_share_photos_layout);
		myImagesCheckBox = (CheckBox) findViewById(R.id.publish_share_photos_checkbox);
		
		faceLinearLayout = (LinearLayout) findViewById(R.id.face_ll);
		faceViewPager = (FaceViewPager) findViewById(R.id.face_pager);
		
	}

	/**
	 * 导航栏的点击事件
	 */
	private void titleClick() {
		//返回
		titleLeftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				if(HSApplication.uploadTempImgList.size()>0||imgList.size()>0){
//					imgList.removeAll(imgList);
//					
//					for(int i=0;i<HSApplication.uploadTempImgList.size();i++){
//						ss.append(HSApplication.uploadTempImgList.get(i).toString()).append("|");
//					}
//					
//					Communication.deleteSharePicture(PublishCircleShareActivity.this,ss.toString());
//					HSApplication.uploadTempImgList.removeAll(HSApplication.uploadTempImgList);
//					
//					
//				}
				
				finish();
			}
		});
		//发表
		titleRightBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pro.show();
				String content = contentEdit.getText().toString()==null?"":contentEdit.getText().toString();
//				for(int i=0;i<HSApplication.uploadTempImgList.size();i++){
//					ss.append(HSApplication.uploadTempImgList.get(i)).append("|");
//				}
				Communication.addCircleShare(PublishCircleShareActivity.this,
						HSApplication.sp.getString("userid",""), 
						HSApplication.sp.getString("username","").toString(), 
						circleId,
						content,//myAddr, 
						"", //@的人  用 | 分割
						"");
			}
		});

	}

	/**
	 * 相关控件的点击事件
	 */
	private void clickListener() {
		// 显示 上传的图片
		photoImgBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					imgLayout.setVisibility(View.VISIBLE);
					photoImgBtn
							.setBackgroundResource(R.drawable.photo_album_select);
				} else {
					imgLayout.setVisibility(View.GONE);
					photoImgBtn
							.setBackgroundResource(R.drawable.photo_album_normal);
				}
			}
		});
		// 显示自己的位置
		positionImgBtn
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							getLocation();
							myLocation.setVisibility(View.VISIBLE);
							positionImgBtn
									.setBackgroundResource(R.drawable.position_select);
						} else {
							myLocation.setVisibility(View.GONE);
							myAddr = "";
							positionImgBtn
									.setBackgroundResource(R.drawable.position_normal);
						}
					}
				});

	}

	/**
	 * 本地照片
	 */
	private void album() {
		Bitmap photo = BitmapFactory.decodeFile(albumImg);
		myImages.setImageBitmap(photo);
		photoImgBtn.setChecked(true);
		imgLayout.setVisibility(View.VISIBLE);
		showGrid();
	}

	/**
	 * 显示GridView(图片--myImages上面有个checkBox)
	 */
	private void showGrid() {
		myImagesCheckBox
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							gridView();
						} else {
							gridLayout.setVisibility(View.GONE);
						}
					}
				});

	}

	/**
	 * 发表分享
	 */
	private void publishEdit() {
//		myImages.setBackgroundResource(R.drawable.ar_btn1);
		myImages.setImageResource(R.drawable.ar_btn1);
		myImagesCheckBox.setVisibility(View.GONE);
		myImages.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(PublishCircleShareActivity.this)
						.setTitle("提示")
						.setItems(new String[] { "拍照", "本地选择", "取消" },
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										switch (which) {
										case 0:// 0：拍照
											camera();
											break;
										case 1:// 1：相册a
											Intent album = new Intent(Intent.ACTION_GET_CONTENT);
											album.setType("image/*");
											startActivityForResult(album, ALBUM_RESULT);
											break;
										case 2:
											dialog.cancel();
											break;
										default:
											break;
										}
									}
								}).show();
			}
		});
	}

	/**
	 * 拍照
	 */
	private void camera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
		// 获得名字
		imagenames = UUID.randomUUID() + ".jpg";
		Filename = Environment.getExternalStorageDirectory() + "/" + imagenames;
		// 下面这句指定调用相机拍照后的照片存储的路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(Filename)));
		intent.putExtra("return-data", true);
		startActivityForResult(intent, CAMERA_RESULT);
	}

	public void imgClick(View v) {
		switch (v.getId()) {
		case R.id.publish_share_at:

			Util.toast(PublishCircleShareActivity.this, "没有找到相关数据");
			break;
		case R.id.publish_share_face:
			//initFacePage();
			if (!isFaceShow) {
				imm.hideSoftInputFromWindow(contentEdit.getWindowToken(), 0);
				try {
					Thread.sleep(80);// 解决此时会黑一下屏幕的问题
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				faceLinearLayout.setVisibility(View.VISIBLE);
				isFaceShow = true;
			} else {
				faceLinearLayout.setVisibility(View.GONE);
				isFaceShow = false;
			}	
			break;

		default:
			break;
		}

	}
	
	// 防止乱pageview乱滚动
	private OnTouchListener forbidenScroll() {
		return new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					return true;
				}
				return false;
			}

		};
	}	

	@Override
	protected void onPause() {
		imm.hideSoftInputFromWindow(contentEdit.getWindowToken(), 0);
		faceLinearLayout.setVisibility(View.GONE);
		isFaceShow = false;		
		super.onPause();

	}
	

	/**
	 * 获得地理位置信息
	 */
	private void getLocation() {

		try {
			HSApplication app = HSApplication.getInstance();
			String province = app.currlocation.getProvince().toString();
			String city = app.currlocation.getCity().toString();
			String area = app.currlocation.getDistrict().toString();
			//myAddr = app.currlocation.getAddrStr().toString();
			StringBuffer sb = new StringBuffer();
			sb.append(province).append(city).append(area);
			myAddr = sb.toString();
			myLocation.setText(myAddr);
			
		} catch (Exception e) {
			Util.toast(PublishCircleShareActivity.this, "网络连接错误");
			e.printStackTrace();
		}

	}

	private void gridView() {
		gridLayout.setVisibility(View.VISIBLE);
		gridView.setAdapter(new GridViewAdapter());

	}
	
	class GridViewAdapter extends BaseAdapter{

		@Override
		public View getView(final int i, View view, ViewGroup viewgroup) {
			ViewHolder viewHolder = null;
			if (view == null) {
				view = LayoutInflater.from(PublishCircleShareActivity.this)
						.inflate(R.layout.publish_share_grid_item, null);
				viewHolder = new ViewHolder();
				viewHolder.img = (ImageView) view
						.findViewById(R.id.publish_share_item_img);
				viewHolder.deleteImg = (ImageView) view
						.findViewById(R.id.publish_share_item_delete_img);
				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}
			
			try {
				viewHolder.img.setImageBitmap(HSApplication.getPhoneAlbum(imgArr[i]));
				viewHolder.img.setScaleType(ImageView.ScaleType.CENTER);
				viewHolder.img.setLayoutParams( new FrameLayout.LayoutParams(90,90));
			} catch (Exception e) {
				gridLayout.setVisibility(View.GONE);
				e.printStackTrace();
			}
			
			viewHolder.deleteImg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					imgList.remove(i);
					notifyDataSetChanged();
				}
			});

			return view;
		}

		@Override
		public long getItemId(int i) {
			// TODO Auto-generated method stub
			return i;
		}

		@Override
		public Object getItem(int i) {
			// TODO Auto-generated method stub
			return i;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return imgList.size();
		}
		
		class ViewHolder {
			ImageView img;
			ImageView deleteImg;
		}
	}

	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		case CAMERA_RESULT:// 拍照
			startPhotoZoom(Uri.fromFile(new File(Filename)));
			break;
		case ALBUM_RESULT://本地
			if(data!=null){
				
				try {
					Uri uri = data.getData();//可以得到图片在Content：//。。。中的地址，把它转化成绝对地址如下
					String[] proj = {MediaStore.Images.Media.DATA};
					//参数：proj 是指查哪一列
					Cursor cursor = getContentResolver().query(uri, proj,null, null, null);
					if(cursor != null){
						int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						if(cursor.getCount()>0 && cursor.moveToFirst()){
							Filename = cursor.getString(column_index);
							String name = Filename.substring(Filename.lastIndexOf("/"));
							imagenames = System.currentTimeMillis()+name.substring(name.indexOf("."));
							startPhotoZoom(data.getData());
						}
					}
				} catch (IllegalArgumentException e) {
					Util.toast(PublishCircleShareActivity.this, "未能找到此图片");
					e.printStackTrace();
				}
				
			}
			break;
		case SAVE_PHOTO_RESULT:// 保存
			if (data != null) {
				try {
					setPicToView(data);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;

		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 剪裁图片的方法
	 * 
	 * @param uri
	 */
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "false");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1.5);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, SAVE_PHOTO_RESULT);
	}

	/**
	 * 保存剪裁之后的图片
	 * 
	 * @param picdata
	 * @throws IOException
	 */
	private void setPicToView(Intent picdata) throws IOException {
		Bundle extras = picdata.getExtras();
		Bitmap photo = null;
		if (extras != null) {
			photo = extras.getParcelable("data");
			// 压缩
			photo = imageZoom(photo);
			File f1 = new File(getCacheDir(), imagenames);
			Filename = getCacheDir() + "/" + imagenames;
			savePic(photo, f1.getPath());
			
//			Communication.uploadSharePicture(PublishCircleShareActivity.this,Filename);
			
//			imgList.add(Filename);
			
			myImages.setImageBitmap(photo);
			photoImgBtn.setChecked(true);
			imgLayout.setVisibility(View.VISIBLE);
			myImagesCheckBox.setVisibility(View.VISIBLE);
		}

	}

	public Bitmap imageZoom(Bitmap bitMap) {
		// 图片允许最大空间 ：单位：KB
		double maxSize = 200.00;
		// 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitMap.compress(Bitmap.CompressFormat.JPEG, 70, baos);// 70 -- 压缩率 ；
																// 100是不压缩、压缩率为0；
		byte[] b = baos.toByteArray();

		// 将字节换成KB
		double mid = b.length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		if (mid > maxSize) {
			// 获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
			// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
					bitMap.getHeight() / Math.sqrt(i));
			return bitMap;
		}

		return bitMap;
	}

	public static void savePic(Bitmap b, String strFileName) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(strFileName);
			if (null != fos) {
				b.compress(Bitmap.CompressFormat.PNG, 70, fos);
				fos.flush();
				fos.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 图片的缩放方法
	 * 
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}
	
	/**
	 * 表情
	 */
	private void initFacePage() {
		Set<String> keySet = HSApplication.getInstance().getFaceMap()
				.keySet();
		keys = new ArrayList<String>();
		keys.addAll(keySet);
		
		List<View> lv = new ArrayList<View>();
		for (int i = 0; i < HSApplication.NUM_PAGE; ++i)
			lv.add(getGridView(i));
		FacePageAdeapter adapter = new FacePageAdeapter(lv, faceViewPager);
		faceViewPager.setAdapter(adapter);
		faceViewPager.setCurrentItem(currentPage);
		faceViewPager.setTransitionEffect(TransitionEffect.CubeOut);
		CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator);
		indicator.setViewPager(faceViewPager);		
		adapter.notifyDataSetChanged();
		faceLinearLayout.setVisibility(View.GONE);
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				currentPage = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// do nothing
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// do nothing
			}
		});
		adapter.notifyDataSetChanged();
		//faceLinearLayout.setVisibility(View.GONE);
		


	}
	private GridView getGridView(int i) {
		GridView gv = new GridView(this);
		gv.setNumColumns(7);
		gv.setSelector(new ColorDrawable(Color.TRANSPARENT));// 屏蔽GridView默认点击效果
		gv.setBackgroundColor(Color.TRANSPARENT);
		gv.setCacheColorHint(Color.TRANSPARENT);
		gv.setHorizontalSpacing(1);
		gv.setVerticalSpacing(1);
		gv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		gv.setGravity(Gravity.CENTER);
		gv.setAdapter(new FaceAdapter(this, i));
		gv.setOnTouchListener(forbidenScroll());
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == HSApplication.NUM) {// 删除键的位置
					int selection = contentEdit.getSelectionStart();
					String text = contentEdit.getText().toString();
					if (selection > 0) {
						String text2 = text.substring(selection - 1);
						if ("]".equals(text2)) {
							int start = text.lastIndexOf("[");
							int end = selection;
							contentEdit.getText().delete(start, end);
							return;
						}
						contentEdit.getText().delete(selection - 1, selection);
					}
				} else {
					int count = currentPage * HSApplication.NUM + arg2;

					String ori = contentEdit.getText().toString();
					int index = contentEdit.getSelectionStart();
					StringBuilder stringBuilder = new StringBuilder(ori);
					stringBuilder.insert(index, keys.get(count));
					contentEdit.setText(stringBuilder.toString());
					contentEdit.setSelection(index + keys.get(count).length());
				}
			}
		});
		return gv;
	}
	
	

}
